{% extends "base.html" %}

{% block title %}任务管理 - MinerU 文档解析系统{% endblock %}

{% block page_title %}任务管理{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 筛选和搜索 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div class="flex flex-col md:flex-row gap-4">
                <select id="statusFilter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">所有状态</option>
                    <option value="pending">等待中</option>
                    <option value="processing">处理中</option>
                    <option value="completed">已完成</option>
                    <option value="failed">失败</option>
                </select>
                
                <select id="modeFilter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">所有模式</option>
                    <option value="sync">同步</option>
                    <option value="async">异步</option>
                </select>
                
                <input type="text" id="searchInput" placeholder="搜索任务ID或文件名..." 
                       class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <button id="refreshBtn" class="btn-primary text-white px-4 py-2 rounded-md hover:bg-blue-700">
                <i class="fas fa-sync-alt mr-2"></i>刷新
            </button>
        </div>
    </div>
    
    <!-- 任务统计 -->
    <div class="grid grid-cols-1 md:grid-cols-5 gap-6 mb-6">
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">总任务数</p>
                    <p class="text-2xl font-bold text-gray-800" id="totalTasks">0</p>
                </div>
                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-tasks text-blue-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">等待中</p>
                    <p class="text-2xl font-bold text-gray-800" id="pendingTasks">0</p>
                </div>
                <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clock text-yellow-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">处理中</p>
                    <p class="text-2xl font-bold text-gray-800" id="processingTasks">0</p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-spinner fa-spin text-orange-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">已完成</p>
                    <p class="text-2xl font-bold text-gray-800" id="completedTasks">0</p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-check-circle text-green-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">失败</p>
                    <p class="text-2xl font-bold text-gray-800" id="failedTasks">0</p>
                </div>
                <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-times-circle text-red-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 任务列表 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">任务列表</h3>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务ID</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件名</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">优先级</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模式</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">进度</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody id="taskTableBody" class="bg-white divide-y divide-gray-200">
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                            <p>加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="flex-1 flex justify-between sm:hidden">
                <button id="prevPageMobile" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    上一页
                </button>
                <button id="nextPageMobile" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    下一页
                </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示 <span id="startItem" class="font-medium">1</span> 到 <span id="endItem" class="font-medium">10</span> 条，
                        共 <span id="totalItems" class="font-medium">0</span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" id="pagination">
                        <!-- 分页按钮将通过JavaScript动态生成 -->
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div id="taskModal" class="modal fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-11/12 max-w-4xl shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">任务详情</h3>
                <button onclick="closeTaskModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div id="taskDetails" class="space-y-4">
                <!-- 任务详情将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPage = 1;
let pageSize = 10;
let totalTasks = 0;

// 页面加载时获取任务列表
document.addEventListener('DOMContentLoaded', function() {
    loadTasks();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    const refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            console.log('刷新按钮被点击');
            loadTasks();
        });
    }
    
    const statusFilter = document.getElementById('statusFilter');
    const modeFilter = document.getElementById('modeFilter');
    const searchInput = document.getElementById('searchInput');
    
    if (statusFilter) {
        statusFilter.addEventListener('change', function() {
            console.log('状态筛选改变:', statusFilter.value);
            loadTasks();
        });
    }
    
    if (modeFilter) {
        modeFilter.addEventListener('change', function() {
            console.log('模式筛选改变:', modeFilter.value);
            loadTasks();
        });
    }
    
    if (searchInput) {
        searchInput.addEventListener('input', debounce(loadTasks, 500));
    }
}

// 加载任务列表
async function loadTasks() {
    try {
        const status = document.getElementById('statusFilter').value;
        const mode = document.getElementById('modeFilter').value;
        const search = document.getElementById('searchInput').value;
        
        let url = `/api/v1/tasks/my-tasks?page=${currentPage}&page_size=${pageSize}`;
        if (status) url += `&status=${status}`;
        if (mode) url += `&mode=${mode}`;
        if (search) url += `&search=${search}`;
        
        console.log('请求URL:', url);
        console.log('筛选条件 - 状态:', status, '模式:', mode, '搜索:', search);
        
        const response = await apiRequest(url);
        console.log('API响应:', response);
        
        // 更新任务列表
        updateTaskTable(response.items || []);
        
        // 更新统计信息
        if (response.stats) {
            console.log('统计信息:', response.stats);
            updateTaskStats(response.stats);
        } else {
            console.warn('API响应中没有统计信息');
        }
        
        // 更新分页
        totalTasks = response.total || 0;
        updatePagination();
        
    } catch (error) {
        console.error('加载任务失败:', error);
        document.getElementById('taskTableBody').innerHTML = `
            <tr>
                <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                    <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                    <p>加载失败</p>
                </td>
            </tr>
        `;
    }
}

// 更新任务表格
function updateTaskTable(tasks) {
    const tbody = document.getElementById('taskTableBody');
    
    if (tasks.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                    <i class="fas fa-inbox text-2xl mb-2"></i>
                    <p>暂无任务</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = tasks.map(task => `
        <tr class="hover:bg-gray-50">
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800">${task.task_id}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800">${task.filename}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="status-badge status-${task.status}">
                    <i class="fas fa-${getStatusIcon(task.status)} mr-1"></i>
                    ${getStatusText(task.status)}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="priority-badge priority-${task.priority}">
                    ${task.priority}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800">${task.execution_mode === 'sync' ? '同步' : '异步'}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center space-x-2">
                    <div class="w-16 bg-gray-200 rounded-full h-2">
                        <div class="bg-${getStatusColor(task.status)}-600 h-2 rounded-full" style="width: ${task.progress}%"></div>
                    </div>
                    <span class="text-sm text-gray-600">${task.progress}%</span>
                </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${formatDate(task.created_at)}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button onclick="viewTaskDetails('${task.task_id}')" class="text-blue-600 hover:text-blue-900 mr-3">
                    <i class="fas fa-eye"></i>
                </button>
                ${task.status === 'processing' ? `
                    <button onclick="cancelTask('${task.task_id}')" class="text-red-600 hover:text-red-900">
                        <i class="fas fa-stop"></i>
                    </button>
                ` : ''}
            </td>
        </tr>
    `).join('');
}

// 更新任务统计
function updateTaskStats(stats) {
    console.log('更新统计信息:', stats);
    
    const totalElement = document.getElementById('totalTasks');
    const pendingElement = document.getElementById('pendingTasks');
    const processingElement = document.getElementById('processingTasks');
    const completedElement = document.getElementById('completedTasks');
    const failedElement = document.getElementById('failedTasks');
    
    if (totalElement) {
        totalElement.textContent = stats.total || 0;
        console.log('设置总任务数:', stats.total || 0);
    } else {
        console.error('找不到totalTasks元素');
    }
    
    if (pendingElement) {
        pendingElement.textContent = stats.pending || 0;
        console.log('设置等待中任务数:', stats.pending || 0);
    } else {
        console.error('找不到pendingTasks元素');
    }
    
    if (processingElement) {
        processingElement.textContent = stats.processing || 0;
        console.log('设置处理中任务数:', stats.processing || 0);
    } else {
        console.error('找不到processingTasks元素');
    }
    
    if (completedElement) {
        completedElement.textContent = stats.completed || 0;
        console.log('设置已完成任务数:', stats.completed || 0);
    } else {
        console.error('找不到completedTasks元素');
    }
    
    if (failedElement) {
        failedElement.textContent = stats.failed || 0;
        console.log('设置失败任务数:', stats.failed || 0);
    } else {
        console.error('找不到failedTasks元素');
    }
}

// 更新分页
function updatePagination() {
    const totalPages = Math.ceil(totalTasks / pageSize);
    const startItem = (currentPage - 1) * pageSize + 1;
    const endItem = Math.min(currentPage * pageSize, totalTasks);
    
    document.getElementById('startItem').textContent = startItem;
    document.getElementById('endItem').textContent = endItem;
    document.getElementById('totalItems').textContent = totalTasks;
    
    // 生成分页按钮
    const pagination = document.getElementById('pagination');
    let paginationHTML = '';
    
    // 上一页按钮
    paginationHTML += `
        <button onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''} 
                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'cursor-not-allowed' : ''}">
            <i class="fas fa-chevron-left"></i>
        </button>
    `;
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHTML += `
                <button onclick="changePage(${i})" class="relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                    i === currentPage 
                        ? 'z-10 bg-blue-50 border-blue-500 text-blue-600' 
                        : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
                }">
                    ${i}
                </button>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHTML += `
                <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                    ...
                </span>
            `;
        }
    }
    
    // 下一页按钮
    paginationHTML += `
        <button onclick="changePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''} 
                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'cursor-not-allowed' : ''}">
            <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = paginationHTML;
}

// 切换页面
function changePage(page) {
    const totalPages = Math.ceil(totalTasks / pageSize);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        loadTasks();
    }
}

// 查看任务详情
async function viewTaskDetails(taskId) {
    try {
        const task = await apiRequest(`/api/v1/tasks/${taskId}`);
        const modal = document.getElementById('taskModal');
        const details = document.getElementById('taskDetails');
        
        details.innerHTML = `
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">任务ID</label>
                    <p class="text-sm text-gray-800">${task.task_id}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">文件名</label>
                    <p class="text-sm text-gray-800">${task.filename}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">状态</label>
                    <span class="status-badge status-${task.status}">
                        <i class="fas fa-${getStatusIcon(task.status)} mr-1"></i>
                        ${getStatusText(task.status)}
                    </span>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">模式</label>
                    <p class="text-sm text-gray-800">${task.execution_mode === 'sync' ? '同步' : '异步'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">进度</label>
                    <div class="flex items-center space-x-2">
                        <div class="w-32 bg-gray-200 rounded-full h-2">
                            <div class="bg-${getStatusColor(task.status)}-600 h-2 rounded-full" style="width: ${task.progress}%"></div>
                        </div>
                        <span class="text-sm text-gray-600">${task.progress}%</span>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">创建时间</label>
                    <p class="text-sm text-gray-800">${formatDate(task.created_at)}</p>
                </div>
                ${task.completed_at ? `
                <div>
                    <label class="block text-sm font-medium text-gray-700">完成时间</label>
                    <p class="text-sm text-gray-800">${formatDate(task.completed_at)}</p>
                </div>
                ` : ''}
                ${task.error_message ? `
                <div class="col-span-2">
                    <label class="block text-sm font-medium text-gray-700">错误信息</label>
                    <p class="text-sm text-red-600">${task.error_message}</p>
                </div>
                ` : ''}
            </div>
            
            ${task.status === 'completed' ? `
            <div class="mt-4 pt-4 border-t">
                <h4 class="text-md font-medium text-gray-800 mb-2">解析结果</h4>
                <div class="space-y-2">
                    <a href="/api/v1/parse/${taskId}/result?format=text" target="_blank" class="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-file-alt mr-2"></i>查看文本
                    </a>
                    <a href="/api/v1/parse/${taskId}/result?format=markdown" target="_blank" class="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-file-code mr-2"></i>查看Markdown
                    </a>
                    <a href="/api/v1/parse/${taskId}/result?format=json" target="_blank" class="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-file-code mr-2"></i>查看JSON
                    </a>
                </div>
            </div>
            ` : ''}
        `;
        
        modal.classList.remove('hidden');
    } catch (error) {
        console.error('获取任务详情失败:', error);
        showNotification('获取任务详情失败', 'error');
    }
}

// 关闭任务详情模态框
function closeTaskModal() {
    document.getElementById('taskModal').classList.add('hidden');
}

// 取消任务
async function cancelTask(taskId) {
    if (!confirm('确定要取消这个任务吗？')) {
        return;
    }
    
    try {
        await apiRequest(`/api/v1/tasks/${taskId}/cancel`, { method: 'POST' });
        showNotification('任务已取消', 'success');
        loadTasks();
    } catch (error) {
        console.error('取消任务失败:', error);
        showNotification('取消任务失败', 'error');
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 状态相关函数
function getStatusIcon(status) {
    const icons = {
        'pending': 'clock',
        'processing': 'spinner fa-spin',
        'completed': 'check-circle',
        'failed': 'times-circle'
    };
    return icons[status] || 'question-circle';
}

function getStatusText(status) {
    const texts = {
        'pending': '等待中',
        'processing': '处理中',
        'completed': '完成',
        'failed': '失败'
    };
    return texts[status] || '未知';
}

function getStatusColor(status) {
    const colors = {
        'pending': 'orange',
        'processing': 'blue',
        'completed': 'green',
        'failed': 'red'
    };
    return colors[status] || 'gray';
}
</script>
{% endblock %}